package com.licq.ldoc.writer.impl;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.licq.ldoc.domain.Element;
import com.licq.ldoc.utils.LowAgieUtils;
import com.licq.ldoc.writer.ElementWriter;
import com.licq.ldoc.writer.visitor.example.ExampleContext;
import com.licq.ldoc.writer.visitor.example.ExampleVisitor;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Table;

public class ExampleWriter implements ElementWriter {

	@Override
	public void write(Element element, Document document)
			throws DocumentException {
		document.add(writeExample(element));
	}

	private Table writeExample(com.licq.ldoc.domain.Element element)
			throws BadElementException {
		Table table = createExampleTable();
		writeExampleData(table, element);
		table.complete();
		return table;
	}

	private Table createExampleTable() throws BadElementException {
		Table table = new Table(1);
		table.setWidth(90);
		table.setPadding(4f);
		return table;
	}

	private void writeExampleData(Table table, Element element)
			throws BadElementException {
		org.dom4j.Document doc = DocumentHelper.createDocument();
		org.dom4j.Element root = doc.addElement(element.getName());
		Object exampleObj = ExampleContext.get(element.getType().getClazz());
		if (exampleObj != null) {
			element.accept(new ExampleVisitor(root, exampleObj));
		}
		Chunk chunk = new Chunk(prettyFormat(doc), LowAgieUtils.BLUE_FONT);
		Cell cell = new Cell(chunk);
		cell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
		cell.setBackgroundColor(new Color(230, 230, 230));
		table.addCell(cell);
	}

	private String prettyFormat(org.dom4j.Document doc) {
		OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
		prettyPrint.setIndentSize(6);
		prettyPrint.setSuppressDeclaration(true);
		OutputStream os = new ByteArrayOutputStream();
		try {
			XMLWriter writer = new XMLWriter(os, prettyPrint);
			writer.write(doc);
			writer.close();
			String content = os.toString();
			return content.substring(1, content.length() - 1);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtils.EMPTY;
		}
	}

}
